const bcrypt = require('bcrypt');
const {User} = require('../../model/user');

module.exports = async(req, res) => {
    let {username, password, email, role} = req.body;
    //  判断用户名是否被使用
    let isValid = await User.find({username: username, role: role});
    if (isValid) {
        res.redirect('admin/add');
    } else {
        //  生成随机字符串
    const  salt = await bcrypt.genSalt;
    //  生成加密密码
    let pass = await bcrypt.hash(password, salt);
    //  将注册用户添加到数据库中
    await User.create({
        username: username,
        password: pass,
        email: email,
        role: role
    });
    //  注册成功后跳转回登陆页面重新登陆
    res.redirect('/admin/login');
    }
}